package com.zcmob.web.admanagement.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import jodd.props.Props;

public class PropsUtils {

    private static Props props = null;
    
    public static void load2SystemProperties(File file) throws IOException {

        props = new Props();
        props.load(file, "UTF-8");
        Properties tmpProperties = props.extractProperties();
        
        for (Map.Entry<Object, Object> entry : tmpProperties.entrySet()) {
            String key = entry.getKey().toString();
            if (key.startsWith(".")) {
                System.setProperty(key.subSequence(1, key.length()).toString(), entry.getValue().toString());
            } else {
                System.setProperty(entry.getKey().toString(), entry.getValue().toString());
            }
        }

    }
    
    public static void loadPropertyFile(File file) throws IOException {
        
        
        props = new Props();
        props.load(file, "UTF-8");

    }
    
    public static Properties getPropertyFile(File file) throws IOException {
        
        Properties result = new Properties();
        
        props = new Props();
        props.load(file, "UTF-8");
        
        Properties tmpProperties = props.extractProperties();
        for (Map.Entry<Object, Object> entry : tmpProperties.entrySet()) {
            String key = entry.getKey().toString();
            if (key.startsWith(".")) {
                result.put(key.subSequence(1, key.length()).toString(), entry.getValue().toString());
            } else {
                result.put(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        
        return result;
    }
    
    public static String getProperty(String key) {
        String result = props.getValue(key);
        
        if (StringUtils.isNullOrEmpty(result)) {
            result = props.getValue(key);
        }
        
        return result;
    }
    
    public static String getValueStringNotNull(String key) throws Exception {
        
        if(getProperty(key) == null || getProperty(key).trim().equals("")){
            throw new Exception("not found " + key + " property in config file ");
        }
        return getProperty(key);
        
    }
    
    public static void main(String[] args) {
        
        try {
            PropsUtils.load2SystemProperties(new File("E:\\tools\\work_space\\dmzapi\\src\\env.properties"));
            System.out.println(PropsUtils.getProperty("iconServerpath"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}
